const baseUrlMap = require('./env')
const accountInfo = wx.getAccountInfoSync()
const { baseUrl } = baseUrlMap[accountInfo.miniProgram.envVersion]
const qxhId = 79
const commonParams = {
  partner: 'minchat',
  partnerChannel: `qxb_minchat_${qxhId}`,
  qxhId
}
if (wx.getStorageSync('deviceToken')) {
  commonParams.deviceToken = wx.getStorageSync('deviceToken')
}
module.exports = {
  postJson: (url, data = {}) => {
    const fullUrl = `${baseUrl}${url}`
    let params
    if (data.common) {
      data.common = { ...commonParams, ...data.common }
      params = data
    } else {
      params = { common: commonParams, ...data }
    }
    return new Promise((resolve, reject) => {
      wx.request({
        url: fullUrl,
        method: 'POST',
        data: params,
        header: {
          'Content-Type': 'application/json;charset=UTF-8'
        },
        success(res) {
          if (res.statusCode === 200) {
            if (res.data.code > 0) {
              resolve(res.data)
            } else {
              wx.showToast({
                title: res.data.message,
                icon: 'error'
              })
              reject(res.data)
            }
          } else {
            wx.showToast({
              title: '请求失败',
              icon: 'error'
            })
            reject(res)
          }
        },
        fail(error) {
          console.log('error', error)
          wx.showToast({
            title: '请求失败',
            icon: 'error'
          })
          reject(error)
        }
      })
    })
  }
}
